#!/bin/sh -ev

unset KDEDIR KDEDIRS
export PATH=`perl -e 'my @path; for (split(/:/, $ENV{PATH})) { if ($_ !~ /^\/(sw|fink)/) { push(@path, $_) } }; print join(":", @path), "\n";'`

# this is in *reverse* order of preference!
for dir in /opt/kde4-deps /opt/kde4 /opt/qt4; do
	[ `echo $PATH               | grep -c -- "$dir/bin:"`           -eq 0 ] && export PATH="$dir/bin:$PATH"
	[ `echo $PKG_CONFIG_PATH    | grep -c -- "$dir/lib/pkgconfig:"` -eq 0 ] && export PKG_CONFIG_PATH="$dir/lib/pkgconfig:$PKG_CONFIG_PATH"
	[ `echo $CMAKE_LIBRARY_PATH | grep -c -- "$dir/lib:"`           -eq 0 ] && export CMAKE_LIBRARY_PATH="$dir/lib:$CMAKE_LIBRARY_PATH"
	[ `echo $CMAKE_INCLUDE_PATH | grep -c -- "$dir/include:"`       -eq 0 ] && export CMAKE_INCLUDE_PATH="$dir/include:$CMAKE_INCLUDE_PATH"
	[ `echo $CPPFLAGS           | grep -c -- "-I$dir/include"`      -eq 0 ] && export CPPFLAGS="$CPPFLAGS -I$dir/include"
	[ `echo $LDFLAGS            | grep -c -- "-L$dir/lib"`          -eq 0 ] && export LDFLAGS="$LDFLAGS -L$dir/lib"
	[ `echo $XDG_DATA_DIRS      | grep -c -- "$dir/share:"`         -eq 0 ] && export XDG_DATA_DIRS="$dir/share:$XDG_DATA_DIRS"
	[ `echo $XDG_CONFIG_DIRS    | grep -c -- "$dir/etc/xdg:"`       -eq 0 ] && export XDG_CONFIG_DIRS="$dir/share:$XDG_CONFIG_DIRS"
done

export PERL5LIB=/opt/kde4-deps/lib/perl5
export CPPFLAGS="$CPPFLAGS -fno-common"

MYID=`id -u`
mkdir -p /tmp/ldfakeroot/$MYID
chmod 1777 /tmp/ldfakeroot
ln -sf /usr/bin/ld64 "/tmp/ldfakeroot/$MYID/ld"
 
export CFLAGS="-B/tmp/$MYID/ldfakeroot"
export CXXFLAGS="-B/tmp/$MYID/ldfakeroot"
export LDFLAGS="-B/tmp/$MYID/ldfakeroot"

if [ -x /usr/local/bin/cmake ]; then
	export PATH="$PATH:/usr/local/bin"
fi

case `uname -s` in
	Linux)
		export CLUCENE_HOME=/usr
		;;
	Darwin)
		export CLUCENE_HOME=/opt/kde4-deps
		OS_VER=`/usr/bin/sw_vers | grep ProductVersion  | awk '{ print $2 }' | cut -d. -f1-2`
		unset DISTCC_HOSTS
		unset CMAKE_OSX_ARCHITECTURES

		export MACOSX_DEPLOYMENT_TARGET="10.4"
		if [ "$DO_UNIVERSAL" = "1" ]; then
			export CMAKE_OSX_ARCHITECTURES="i386;ppc"
			export CMAKE_OSX_SYSROOT="/Developer/SDKs/MacOSX10.4u.sdk"
			export CCACHE_DISABLE=1
		fi

		CPUS=`sysctl -n hw.ncpu 2>/dev/null`
		CORES=`sysctl -n machdep.cpu.cores_per_package 2>/dev/null`

		[ -z "$CPUS"  ] && CPUS=1
		[ -z "$CORES" ] && CORES=1

		CPUS=`expr $CPUS '*' $CORES 2>&1`
		[ -z "$CPUS"  ] && CPUS=1

		export MAKEFLAGS=-j$CPUS
		;;
esac
